package com.dx.oa.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 定义拦截器类
 * 用于登录验证的拦截器
 * 实现HandlerInterceptor接口
 * @author dx911
 *
 */
public class LoginInterceptor implements HandlerInterceptor{


	/**
	 * 访问之前的工作
	 * 类似访问前的登录验证
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		
		//需要过滤匿名访问地址
		String uri = request.getRequestURI();
		if(uri.indexOf("login") >= 0 || uri.indexOf("Login") >=0)
			return true;
		HttpSession session = request.getSession();
		if(session.getAttribute("user") != null)
		{
			return true;
		}
		else
		{
			System.out.println("请重新登录");
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);;
		}
		return false;
	}
	
	/**
	 * 在执行handler方法中，返回ModelAndView之前,运行这个方法里面的代码
	 * 向页面提供一些公用数据或者视图信息
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//System.out.println(request.getRequestURI() + ":" + Thread.currentThread().getStackTrace()[1].getClassName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());
	}

	/**
	 * 执行handler方法之后，运行这里面的代码
	 * 比如统计异常
	 * 计算某个handler方法的执行时间:afterCompletion - prehandler
	 * 统一的日志记录
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//System.out.println(request.getRequestURI() + ":" + Thread.currentThread().getStackTrace()[1].getClassName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());
	}

}
